<?php

namespace Home\Controller;

use Home\Model\ClassModel;
use Home\Model\UserModel;
use Think\Controller;

class ChooseController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['role'] == 2) {
            $this->retError('学生才可以选课');
        }
    }


    public function index()
    {
        $choose = M('ChooseClass'); // 实例化User对象
        $query = $choose->where('stu_id', $this->user['id']);
        $count = $query->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $query->order('create_time')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($list as $key => $item) {
            $class = (new ClassModel())->where('id', $item['class_id'])->select()[0];;
            $item['class'] = $class['name'];
            $item['time'] = $class['time'];
            $item['address'] = $class['address'];
            $list[$key] = $item;
        }
        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    public function create()
    {
        $choose = M('ChooseClass'); // 实例化User对象
        $class = new ClassModel(); // 实例化User对象
        $query = $class;
        $count = $query->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $query->order('create_time')->limit($Page->firstRow . ',' . $Page->listRows)->select();

        $user = new UserModel();
        foreach ($list as $key => $item) {
            $item['teacher'] = $user->where('id', $item['id'])->select()[0]['name'];
            $item['already'] = count($choose->where('class_id', $item['id'])->select());
            $list[$key] = $item;
        }

        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    public function store()
    {
        $class = M('ChooseClass');

        $result = $class->where('class_id', I('post.class_id'))->where('stu_id', $this->user['id'])->select();
        if ($result) {
            $this->retError('已报名此课程');
        }

        $data = I('post.');
        $data['stu_id'] = $this->user['id'];
        $data['create_time'] = time();
        $data['update_time'] = time();
        $class->create($data);
        $result = $class->add();
        if (!$result) {
            $this->retError('新增失败');
        } else {
            $this->retSuccess();
        }
    }
}